﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IHISCETeim.Library;
using System.Data;
using IHISCETeim.BLL;
using System.Text;
using IHISCETeim.Model;
namespace IHISCETeim.Web.MachineSys.FTradeModel
{
    public partial class ReportZhanLin2EasyUI_YuQiDetail : EasyUIPageBase
    {
        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.查看 };
            }
        }
        protected override string DWZRef
        {
            get
            {
                return "ReportZhanLin2EasyUI";
            }
        }

        protected string GetXiaoShouLeiXing()
        {
            List<FTradeSaleTypeConfigInfo> list = FTradeSaleTypeConfigController.GetAll();
            StringBuilder sb = new StringBuilder();
            string JSONTemp = "{{label: '{0}',value: '{1}'}},";
            sb.Append("");
            foreach (FTradeSaleTypeConfigInfo itm in list)
            {
                sb.AppendFormat(JSONTemp, itm.XiaoShouLeiXing, itm.XiaoShouLeiXing);
                // sb.AppendFormat("<option value=\"{0}\" {1}>{0}</option>", itm.XiaoShouLeiXing, itm.XiaoShouLeiXing == XiaoShouLeiXing ? "selected" : "");
            }

            return sb.ToString().Substring(0, sb.ToString().Length - 1);
        }
        protected string GetZDXiaoShouState()
        {
            List<FTradeSaleTypeConfigInfo> list = FTradeSaleTypeConfigController.GetAll();
            string[] zds = new string[] { "--所有状态--", "融资租赁(已放款)", "全款", "融资租赁(未放款)", "库存车", "分期", "按揭" };
            StringBuilder sb = new StringBuilder();
            string JSONTemp = "{{label: '{0}',value: '{1}'}},";
            sb.Append("");
            foreach (string itm in zds)
            {
                sb.AppendFormat(JSONTemp, itm, itm);
                // sb.AppendFormat("<option value=\"{0}\" {1}>{0}</option>", itm.XiaoShouLeiXing, itm.XiaoShouLeiXing == XiaoShouLeiXing ? "selected" : "");
            }

            return sb.ToString().Substring(0, sb.ToString().Length - 1);
        }
        #region 属性 (查询条件)
        /// <summary>
        /// 是否从报表8分期汇总过来,如果是1,刚只显示分期相关数据
        /// </summary>
        protected int IsShowFenQi
        {
            get
            {
                return GetRequestValue<int>("IsShowFenQi", 1);
            }
        }
        protected string JingXiaoShang
        {
            get
            {
                return GetRequestValue<string>("JingXiaoShang", "");

            }
        }
        protected string HeTongHao
        {
            get
            {
                return GetRequestValue<string>("HeTongHao", "");

            }
        }

        protected string JiHao
        {
            get
            {
                return GetRequestValue<string>("JiHao", "");

            }
        }

        protected string JiQiState
        {
            get
            {
                return GetRequestValue<string>("JiQiState", "-");
            }
        }

        protected string XiaoShouShiJianFrom
        {
            get
            {
                return GetRequestValue<string>("XiaoShouShiJianFrom", "");

            }
        }
        protected string XiaoShouShiJianTo
        {
            get
            {
                if (string.IsNullOrEmpty(XiaoShouShiJianFrom))
                {
                    return "";
                }
                else
                {
                    string todate = GetRequestValue<string>("XiaoShouShiJianTo", "");
                    if (string.IsNullOrEmpty(todate))
                        return Convert.ToDateTime(XiaoShouShiJianFrom).AddDays(1).ToShortDateString();
                    else
                        return todate;
                }

            }
        }

        protected string ZDXiaoShouState
        {
            get
            {
                return GetRequestValue<string>("ZDXiaoShouState", "");

            }
        }
        //收款条件
        private string _XiaoShouLeiXing = "";
        protected string XiaoShouLeiXing
        {
            get
            {
                if (_XiaoShouLeiXing == "")
                    _XiaoShouLeiXing = GetRequestValue<string>("XiaoShouLeiXing", "");
                return _XiaoShouLeiXing;
            }
            set
            {
                _XiaoShouLeiXing = value;
            }
        }
        protected string GetSQLWhere(int type)
        {
            string wheresql = " WeiShouKuanXiang>0 and " + (type == 1 ? sqlwherestr1 : sqlwherestr2);
            string sqlcommonFiled = "";
            if (!string.IsNullOrEmpty(JingXiaoShang))
            {              
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("JingXiaoShang", QueryOperatorsEnum.等于, JingXiaoShang);               

                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }

            }



            if (!string.IsNullOrEmpty(HeTongHao))
            {
                string DOWNSQL = QueryOperatorsEnumHelper.ConvertCommonOperator("HeTongHao", QueryOperatorsEnum.等于, HeTongHao);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + DOWNSQL;
                }
                else
                {
                    wheresql = DOWNSQL;
                }
            }


            if (!string.IsNullOrEmpty(XiaoShouShiJianFrom))
            {
                string DOWNSQL = QueryOperatorsEnumHelper.ConvertCommonOperator("XiaoShouShiJian", QueryOperatorsEnum.范围, XiaoShouShiJianFrom + "|" + XiaoShouShiJianTo);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + DOWNSQL;
                }
                else
                {
                    wheresql = DOWNSQL;
                }
            }



            string dutySQL = "";
            if (!string.IsNullOrEmpty(JiHao))
            {
                dutySQL = QueryOperatorsEnumHelper.ConvertCommonOperator("JiHao", QueryOperatorsEnum.包含, JiHao);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + dutySQL;
                }
                else
                {
                    wheresql = dutySQL;
                }
            }

            if (JiQiState != "-")
            {
                string DOWNSQL = QueryOperatorsEnumHelper.ConvertCommonOperator("JiQiState", QueryOperatorsEnum.等于, JiQiState);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + DOWNSQL;
                }
                else
                {
                    wheresql = DOWNSQL;
                }
            }
           
            //2014.04-22
            if (ZDXiaoShouState != "--所有状态--" && ZDXiaoShouState != "")
            {
                string DOWNSQL = QueryOperatorsEnumHelper.ConvertCommonOperator("ZDXiaoShouState", QueryOperatorsEnum.等于, ZDXiaoShouState);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + DOWNSQL;
                }
                else
                {
                    wheresql = DOWNSQL;

                }
            }
            return wheresql;
        }

       
        #endregion

        #region 设置条件

        private string sqlwherestr1 = "";
        private string sqlwherestr2 = "";
        private void SetDate()
        {
            int minDay = (YuQiTag != "day360more" && YuQiTag != "weidaoqikuanxing") ? Convert.ToInt32(YuQiTag.Replace("day", "")) : 0;//60天以后
            int maxDay = minDay - 30;
            switch (YuQiTag)
            {
                case "day30":
                    sqlwherestr1 = " FTradeReceivables.FTradeSalesId in(SELECT subAge.FTradeSalesId FROM dbo.FTradeAgeDetail AS subAge WHERE subAge.State='正常' and  (subAge.DaoQiRi < GETDATE()) AND (DATEDIFF(DAY, subAge.DaoQiRi, GETDATE()) <= 30))";
                    sqlwherestr2 = " FTradeAgeDetail.State='正常' and  (FTradeAgeDetail.DaoQiRi < GETDATE()) AND (DATEDIFF(DAY, FTradeAgeDetail.DaoQiRi, GETDATE()) <= 30)";
                   
                    break;
                case "day360more":
                    sqlwherestr1 = " FTradeReceivables.FTradeSalesId in(SELECT subAge.FTradeSalesId FROM dbo.FTradeAgeDetail AS subAge WHERE subAge.State='正常' and  (subAge.DaoQiRi < GETDATE()) AND (DATEDIFF(DAY, subAge.DaoQiRi, GETDATE()) >360))";
                    sqlwherestr2 = " FTradeAgeDetail.State='正常' and  (FTradeAgeDetail.DaoQiRi < GETDATE()) AND (DATEDIFF(DAY, FTradeAgeDetail.DaoQiRi, GETDATE()) >360)";
                  
                    break;
                case "weidaoqikuanxing":
                    sqlwherestr1 = " FTradeReceivables.FTradeSalesId in(SELECT subAge.FTradeSalesId FROM dbo.FTradeAgeDetail AS subAge WHERE subAge.State='正常' and  (subAge.DaoQiRi > GETDATE()))";
                    sqlwherestr2 = " FTradeAgeDetail.State='正常' and  (FTradeAgeDetail.DaoQiRi > GETDATE())";
                   
                    break;
                default:
                    sqlwherestr1 = String.Format(" FTradeReceivables.FTradeSalesId in(SELECT subAge.FTradeSalesId FROM dbo.FTradeAgeDetail AS subAge WHERE subAge.State='正常' and  (subAge.DaoQiRi < GETDATE()) AND (DATEDIFF(DAY, subAge.DaoQiRi, GETDATE()) > {0}) and (DATEDIFF(DAY, subAge.DaoQiRi, GETDATE()) <= {1}))", maxDay, minDay);
                    sqlwherestr2 = string.Format(" FTradeAgeDetail.State='正常' and  (FTradeAgeDetail.DaoQiRi < GETDATE()) and (DATEDIFF(DAY, FTradeAgeDetail.DaoQiRi, GETDATE()) > {0}) AND (DATEDIFF(DAY, FTradeAgeDetail.DaoQiRi, GETDATE()) <= {1})", maxDay, minDay);
                   
                    break;
               
            }
            
        }
        /// <summary>
        /// 参数,即报表应收帐款帐领表的字段名
        /// </summary>
        protected string YuQiTag
        {
            get {
                return GetRequestValue<string>("yuqitag", "day30").ToLower().Trim();
            }
        }

        #endregion

        protected override string query()
        {
            SetDate();

            DataTableCollection dts = FTradeReceivablesController.GetPagination(GetSQLWhere(1), pageNum, numPerPage, SQLSort, ref TotalCount);

            //帐龄信息加工
            DataTable DaoQiRidt = FTradeReportController.GetMinMaxDaoQiRi(GetSQLWhere(2));
            DateTime minDaoQiRi;
            DateTime maxDaoQiRi;
            if (DaoQiRidt.Rows.Count <= 0)
            {
                minDaoQiRi = DateTime.Now;
                maxDaoQiRi = DateTime.Now;
            }
            else
            {
                minDaoQiRi = DaoQiRidt.Rows[0]["minDaoQiRi"] is DBNull ? DateTime.Now : Convert.ToDateTime(DaoQiRidt.Rows[0]["minDaoQiRi"]);
                maxDaoQiRi = DaoQiRidt.Rows[0]["maxDaoQiRi"] is DBNull ? DateTime.Now : Convert.ToDateTime(DaoQiRidt.Rows[0]["maxDaoQiRi"]);
            }
            //获取帐龄明细
            DataTable AgeDetailJinEDT = FTradeReportController.Report1GetAgeDetailJinE(GetSQLWhere(2));
            //到期日列添加
            DataTable dtList = dts[0];
            DataTable dtSumList = dts[1];
            for (DateTime dtTemp = minDaoQiRi; dtTemp < maxDaoQiRi.AddMonths(1); dtTemp = dtTemp.AddMonths(1))
            {
                dtList.Columns.Add(dtTemp.ToString("yyyy-MM"), typeof(string));
                dtSumList.Columns.Add(dtTemp.ToString("yyyy-MM"), typeof(string));
            }
            //获取列值
            for (DateTime dtTemp = minDaoQiRi; dtTemp < maxDaoQiRi.AddMonths(1); dtTemp = dtTemp.AddMonths(1))
            {
                string startDT = dtTemp.ToString("yyyy-MM-01");
                string endDT = Convert.ToDateTime(dtTemp.AddMonths(1).ToString("yyyy-MM-01")).AddDays(-1).ToString("yyyy-MM-dd");
                foreach (DataRow dr in dtList.Rows)
                {
                    object JinE = AgeDetailJinEDT.Compute("sum(JinE)", string.Format(" FTradeID={0} and DaoQiRi >= '{1}' and DaoQiRi<='{2}' ", dr["FTradeID"], startDT, endDT));
                    dr[dtTemp.ToString("yyyy-MM")] = JinE;
                }
                object sumJinE = AgeDetailJinEDT.Compute("sum(JinE)", string.Format(" DaoQiRi >= '{0}' and DaoQiRi<='{1}' ", startDT, endDT));
                dtSumList.Rows[0][dtTemp.ToString("yyyy-MM")] = sumJinE;
            }
            return ToDataGridJson(dtList, TotalCount, dtSumList).ToString();
        }


        #region 获取列JS代码
        private class GridColumnInfo
        {
            public string title { get; set; }
            public string field { get; set; }
            public int width { get; set; }
            public bool sortable { get; set; }
            public string formatter { get; set; }
        }

        protected string GetGirdColumns()
        {
            SetDate();

            DataTable DaoQiRidt = FTradeReportController.GetMinMaxDaoQiRi(GetSQLWhere(2));

            DateTime minDaoQiRi = DaoQiRidt.Rows[0]["minDaoQiRi"] is DBNull ? DateTime.Now : Convert.ToDateTime(DaoQiRidt.Rows[0]["minDaoQiRi"]);// Convert.ToDateTime(DaoQiRidt.Rows[0]["minDaoQiRi"]);
            DateTime maxDaoQiRi =  Convert.ToDateTime(DaoQiRidt.Rows[0]["maxDaoQiRi"]);
           
            List<GridColumnInfo> columnsList = new List<GridColumnInfo>();

            //到期日列添加
            for (DateTime dtTemp = minDaoQiRi; dtTemp < maxDaoQiRi.AddMonths(1); dtTemp = dtTemp.AddMonths(1))
            {
                GridColumnInfo gcItem = new GridColumnInfo();
                gcItem.title = dtTemp.ToString("yyyy-MM");
                gcItem.field = dtTemp.ToString("yyyy-MM");
                gcItem.width = 70;
                gcItem.sortable = false;
                gcItem.formatter = "milliformatter";

                columnsList.Add(gcItem);
            }

            StringBuilder sb = new StringBuilder();
            foreach (GridColumnInfo itm in columnsList)
            {
                sb.AppendFormat("{{ title: '{0}', field: '{1}', width: {2}, sortable: {3} {4}}},", itm.title, itm.field, itm.width, itm.sortable.ToString().ToLower(), string.IsNullOrEmpty(itm.formatter) ? "" : ",formatter:" + itm.formatter);
            }

            //返回COLUMNS JS
            return sb.ToString().Remove(sb.ToString().Length - 1, 1);



        }

        #endregion
    }
}